package com.cc.springboot_test.config;


import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Configuration
public class ElasticSearchConfig {

    private final static Logger logger = LoggerFactory.getLogger(ElasticSearchConfig.class);

    @Value("${es.server.addr}")
    private String addr;

    @Value("${es.cluster.name}")
    private String cluster;

    /*@Value("${es.is.using.searchguard}")
    private String isUsingSearchguard;

    @Value("${es.searchguard.pemkey.filepath}")
    private String pemkeyFilepath;

    @Value("${es.searchguard.pemcert.filepath}")
    private String pemcertFilepath;

    @Value("${es.searchguard.pemtrustedcas.filepath}")
    private String pemtrustedcasFilepath;

    @Value("${es.searchguard.pemkey.password}")
    private String pemkeyPassword;*/

    @Bean(name = "client")
    public TransportClient getClient() {
        logger.info("cluster={}, addr={}", cluster, addr);
        return getClient(cluster, addr);
    }

    private TransportClient getClient(String clusterName, String addr) {
        TransportClient client = null;
        try {
            Settings settings = null;
            Settings.Builder builder = Settings.builder().put("cluster.name", clusterName);
            settings = builder.build();

            String[] ips = getIps(addr);
            String[] ports = getPorts(addr);

            client = new PreBuiltTransportClient(settings);

            for (int i = 0; i < ips.length; i++) {
                client.addTransportAddress(new TransportAddress(InetAddress.getByName(ips[i]), Integer.parseInt(ports[i])));
            }

        } catch (UnknownHostException e) {
            if (null != client) {
                client.close();
            }
            logger.error("获取ES集群连接失败！服务器地址配置出错或ES集群未启动：", e);
        }
        return client;
    }

    private String[] getIps(String addrStr) {
        String[] addrs = addrStr.split(",");
        String[] ips = new String[addrs.length];
        int i = 0;
        for (String addr : addrs) {
            String[] strs = addr.split(":");
            ips[i++] = strs[0];
        }
        return ips;
    }

    private String[] getPorts(String addrStr) {
        String[] addrs = addrStr.split(",");
        String[] ports = new String[addrs.length];
        int i = 0;
        for (String addr : addrs) {
            String[] strs = addr.split(":");
            ports[i++] = strs[1];
        }
        return ports;
    }
}
